package com.himiotech.core.project.web.support;

import com.himiotech.core.framework.config.HimioConfig;
import com.himiotech.core.framework.config.server.ServerInfo;
import com.himiotech.core.framework.helper.utils.file.FileUploadUtils;
import com.himiotech.core.project.service.impl.FileManagerServiceImpl;
import com.himiotech.core.project.web.base.HimioBaseController;
import com.himiotech.core.project.web.base.model.HimioResult;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author wuwenbin
 */
@Controller
@RequestMapping("/system/file/manager")
public class FileManagerController extends HimioBaseController {

    @Autowired
    private FileManagerServiceImpl fileManagerService;
    @Autowired
    private ServerInfo serverInfo;

    @GetMapping
    @RequiresPermissions("system:fileManager:view")
    public String index() {
        return "system/fileManager";
    }

    @GetMapping("/list")
    @ResponseBody
    @RequiresPermissions("system:fileManager:list")
    public HimioResult list(String dir) {
        Object list = fileManagerService.getFileListByDir(dir);
        return writeJsonOkData(list);
    }


    /**
     * 添加文件夹
     *
     * @param dir
     * @param name
     * @return
     */
    @PostMapping("/addFolder")
    @ResponseBody
    public HimioResult addFolder(String dir, String name) {
        fileManagerService.addFolder(dir, name);
        return writeJsonOk("添加文件夹成功");
    }

    /**
     * 通用上传请求
     */
    @ResponseBody
    @PostMapping("/upload")
    @RequiresPermissions("system:fileManager:upload")
    public HimioResult uploadFile(MultipartFile file, String dirPath) throws Exception {
        try {
            // 上传文件路径
            String filePath = HimioConfig.getUploadPath() + dirPath;
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.uploadWithPath(filePath, file);
            String url = serverInfo.getUrl() + fileName;
            HimioResult ajax = HimioResult.okMsg("上传成功");
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            return ajax;
        } catch (Exception e) {
            return writeJsonErr(e.getMessage());
        }
    }

    @ResponseBody
    @PostMapping("/remove")
    @RequiresPermissions("system:fileManager:remove")
    public HimioResult remove(String filePath, String fileName) {
        String absPath = HimioConfig.getUploadPath() + filePath + "/" + fileName;
        boolean result = fileManagerService.removeFile(absPath);
        return writeJson(result);
    }
}
